package ru.voice2blog.engine;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.voice2blog.common.exception.InitException;
import ru.voice2blog.common.exception.PrepareException;
import ru.voice2blog.common.exception.PublishException;
import ru.voice2blog.common.exception.UploadException;
import ru.voice2blog.common.publisher.PublishResult;
import ru.voice2blog.common.publisher.Publisher;
import ru.voice2blog.common.uploader.DataUploader;
import ru.voice2blog.common.uploader.UploadResult;

import java.io.File;
import java.util.Properties;


/**
 * User: ilya.ufo
 * Date: 20.03.11
 * Time: 16:36
 */
public class V2BFramework {

    private boolean wasInitialized = false;

    DataUploader uploader;
    Publisher publisher;

    private static final Logger logger = LoggerFactory.getLogger(V2BFramework.class);

    V2BFramework() {

    }

    /**
     * Производить загрузку файла на хостинг и опубликование ссылки.
     */
    public boolean post(File file) throws UploadException, PublishException, PrepareException {
        logger.info("Starting upload file " + file.getName());
        uploader.prepare(null);
        UploadResult uploadResult = uploader.upload(file);
        uploader.clean();
        if (!uploadResult.isSuccess()) {
            logger.warn("Error on uploading of file {}", file);
            return false;
        }
        logger.info("Uploaded successfully! Link to file is {}", uploadResult.getPath());

        logger.info("Starting publishing link...");
        publisher.prepare(null);
        PublishResult publishResult = publisher.publish(uploadResult.getPath());
        publisher.clean();
        logger.info("Published {}!", (publishResult.isSuccess() ? "successfully" : "failed"));

        return publishResult.isSuccess();
    }

    public DataUploader getUploader() {
        return uploader;
    }

    public Publisher getPublisher() {
        return publisher;
    }

    void initModules(Properties storeProperties, Properties publishProperties) throws InitException {
        uploader.init(storeProperties);
        publisher.init(publishProperties);
        wasInitialized = true;
    }

    public boolean isWasInitialized() {
        return wasInitialized;
    }
}

